package com.youdao.note.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filter.FilterResults;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.youdao.note.LogRecorder;
import com.youdao.note.YNoteApplication;
import com.youdao.note.data.BaseData;
import com.youdao.note.data.ListNoteMetas;
import com.youdao.note.data.NoteMeta;
import com.youdao.note.data.adapter.SectionAdapter;
import com.youdao.note.datasource.DataSource;
import com.youdao.note.provider.SearchSuggestProvider;
import com.youdao.note.task.TaskManager;
import com.youdao.note.utils.CursorHelper;
import com.youdao.note.utils.L;
import com.youdao.note.utils.StringUtils;
import com.youdao.note.utils.UIUtilities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class SearchActivity extends BaseListFileActivity
  implements TextView.OnEditorActionListener, TextWatcher, View.OnClickListener
{
  private static final String BUNDLE_KEYWORD = "keyword";
  private static final String EXTRA_NOTES = "extra_notes";
  private static final int QUERY_LOADING = 1;
  private String EMPTY_TEMPLATE = null;
  private ImageButton clearButton = null;
  private AsyncTask<String, Void, ListNoteMetas> localSearcher = null;
  private TextView mEmptyText = null;
  private String mKeyWord = null;
  private ListNoteMetas mListNoteMetas = null;
  private ProgressDialog mQueryDialog = null;
  ArrayAdapter<String> mQueryHistoryAdapter = null;
  private AutoCompleteTextView mTextView = null;
  private boolean showingHistory = true;

  private void checkUpdateSearchHistryDb()
  {
    List localList = this.mDataSource.getAllSearchHistoryList();
    if (localList.size() <= 0)
      return;
    new Thread(localList)
    {
      public void run()
      {
        ContentResolver localContentResolver = SearchActivity.this.getContentResolver();
        ContentValues localContentValues = new ContentValues();
        Uri localUri = Uri.parse("content://" + SearchSuggestProvider.AUTHORITY + "/suggestions");
        Iterator localIterator = this.val$searchList.iterator();
        while (localIterator.hasNext())
        {
          String str = (String)localIterator.next();
          localContentValues.put("query", str);
          localContentResolver.insert(localUri, localContentValues);
          L.d(SearchActivity.class, str + " added to new search history db");
        }
        SearchActivity.this.mDataSource.clearSearchHistory();
      }
    }
    .start();
  }

  private void doLocalSearch()
  {
    if (this.localSearcher != null)
      this.localSearcher.cancel(true);
    if (this.mYNote.isLogin())
      UIUtilities.showToast(this, 2131361874);
    2 local2 = new AsyncTask()
    {
      protected ListNoteMetas doInBackground(String[] paramArrayOfString)
      {
        return SearchActivity.this.mDataSource.searchNotes(paramArrayOfString[0]);
      }

      public void onPostExecute(ListNoteMetas paramListNoteMetas)
      {
        SearchActivity.this.onUpdate(10, paramListNoteMetas, true);
      }
    };
    String[] arrayOfString = new String[1];
    arrayOfString[0] = this.mKeyWord;
    this.localSearcher = local2.execute(arrayOfString);
  }

  private void performSearch()
  {
    if (!StringUtils.isBlank(this.mKeyWord))
    {
      this.mKeyWord = this.mKeyWord.trim();
      this.mLogRecorder.addSearchTimes();
      new SearchRecentSuggestions(this, SearchSuggestProvider.AUTHORITY, 1).saveRecentQuery(this.mKeyWord, null);
      this.mDataSource.saveSearchQuery(this.mKeyWord);
      showDialog(1);
      if ((!this.mYNote.isNetworkAvailable()) || (!this.mYNote.isLogin()))
        break label97;
      this.mTaskManager.searchNotes(this.mKeyWord);
    }
    return;
    label97: doLocalSearch();
  }

  private void renderSearchResult()
  {
    if (this.showingHistory)
    {
      findViewById(2131165273).setVisibility(8);
      this.showingHistory = false;
    }
    if (this.mListNoteMetas.getFileMetas().length == 0)
    {
      setListAdapter(null);
      TextView localTextView = this.mEmptyText;
      String str = this.EMPTY_TEMPLATE;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = this.mKeyWord;
      localTextView.setText(String.format(str, arrayOfObject));
    }
    while (true)
    {
      L.d(this, "Search result got");
      return;
      Resources localResources = getResources();
      setListAdapter(new SectionAdapter(getLayoutInflater(), this.mListNoteMetas.getFileMetas(), localResources.getString(2131361858), localResources.getString(2131361859)));
    }
  }

  private void setAndFilterSearchResult(ListNoteMetas paramListNoteMetas)
  {
    this.mListNoteMetas = paramListNoteMetas;
    ArrayList localArrayList = new ArrayList();
    for (NoteMeta localNoteMeta1 : this.mListNoteMetas.getFileMetas())
    {
      NoteMeta localNoteMeta2 = this.mDataSource.getNoteMetaById(localNoteMeta1.getNoteId());
      if (localNoteMeta2 == null)
        continue;
      localArrayList.add(localNoteMeta2);
    }
    Collections.sort(localArrayList, NoteMeta.TIME_REVERSE_COMPARATOR);
    if (this.mListNoteMetas.getTotalNumber() == this.mListNoteMetas.getFileMetas().length)
      this.mListNoteMetas.setTotalNumber(localArrayList.size());
    this.mListNoteMetas.setFileMetas((NoteMeta[])localArrayList.toArray(new NoteMeta[0]));
  }

  private void setHistoryAdapter(ListAdapter paramListAdapter)
  {
    if ((paramListAdapter == null) || (paramListAdapter.getCount() == 0))
    {
      this.mEmptyText.setText(2131361877);
      setListAdapter(null);
      return;
    }
    setListAdapter(paramListAdapter);
  }

  public void afterTextChanged(Editable paramEditable)
  {
    if (TextUtils.isEmpty(this.mTextView.getText().toString()))
      UIUtilities.makeViewGone(this.clearButton);
    do
      return;
    while (this.clearButton.getVisibility() != 8);
    UIUtilities.makeViewVisiable(this.clearButton);
  }

  public void beforeTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3)
  {
  }

  protected void bindControlls()
  {
    findViewById(2131165357).setOnClickListener(this);
    this.mTextView.setOnEditorActionListener(this);
    this.clearButton.setOnClickListener(this);
  }

  public Cursor getAllSearchHistory()
  {
    return getContentResolver().query(Uri.parse("content://" + SearchSuggestProvider.AUTHORITY + "/suggestions"), null, null, null, null);
  }

  public List<String> getAllSearchHistoryList()
  {
    HashSet localHashSet = new HashSet();
    Cursor localCursor = getAllSearchHistory();
    ArrayList localArrayList;
    CursorHelper localCursorHelper;
    try
    {
      localArrayList = new ArrayList(localCursor.getCount());
      localCursorHelper = new CursorHelper(localCursor);
      do
        if (!localCursor.moveToNext())
          break label107;
      while (localHashSet.contains(localCursorHelper.getString("query")));
      localArrayList.add(localCursorHelper.getString("query"));
    }
    finally
    {
      localCursor.close();
    }
    label107: Collections.reverse(localArrayList);
    localCursor.close();
    return localArrayList;
  }

  protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
  {
    if ((paramInt1 == 0) && (paramInt2 == 1))
    {
      setAndFilterSearchResult(this.mListNoteMetas);
      renderSearchResult();
      return;
    }
    super.onActivityResult(paramInt1, paramInt2, paramIntent);
  }

  public void onClick(View paramView)
  {
    if (paramView.getId() == 2131165288)
      this.mTextView.setText("");
    do
      return;
    while (paramView.getId() != 2131165357);
    this.mKeyWord = this.mTextView.getText().toString();
    performSearch();
  }

  public void onCreate(Bundle paramBundle)
  {
    requestWindowFeature(1);
    setContentView(2130903109);
    super.onCreate(paramBundle);
    checkUpdateSearchHistryDb();
    this.mKeyWord = getIntent().getStringExtra("query");
    this.mTextView = ((AutoCompleteTextView)findViewById(2131165287));
    this.mTextView.setAdapter(new SearchAdapter());
    this.mTextView.requestFocus();
    this.mTextView.addTextChangedListener(this);
    this.clearButton = ((ImageButton)findViewById(2131165288));
    this.mEmptyText = ((TextView)findViewById(2131165293));
    this.EMPTY_TEMPLATE = getResources().getString(2131361878);
    this.mQueryHistoryAdapter = new ArrayAdapter(this, 2130903110, 2131165355, getAllSearchHistoryList());
    setHistoryAdapter(this.mQueryHistoryAdapter);
    bindControlls();
    performSearch();
  }

  protected Dialog onCreateDialog(int paramInt)
  {
    switch (paramInt)
    {
    default:
      return null;
    case 1:
    }
    this.mQueryDialog = new ProgressDialog(this);
    this.mQueryDialog.setMessage(getResources().getText(2131361947));
    this.mQueryDialog.setIndeterminate(true);
    this.mQueryDialog.setCancelable(true);
    this.mQueryDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
    {
      public void onCancel(DialogInterface paramDialogInterface)
      {
        SearchActivity.this.mTaskManager.stopAll();
      }
    });
    return this.mQueryDialog;
  }

  public boolean onCreateOptionsMenu(Menu paramMenu)
  {
    new MenuInflater(this).inflate(2131034116, paramMenu);
    return true;
  }

  public boolean onEditorAction(TextView paramTextView, int paramInt, KeyEvent paramKeyEvent)
  {
    if (paramInt == 3)
    {
      this.mKeyWord = this.mTextView.getText().toString();
      performSearch();
      return true;
    }
    return false;
  }

  public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong)
  {
    if (this.showingHistory)
    {
      this.mKeyWord = ((String)this.mQueryHistoryAdapter.getItem(paramInt));
      performSearch();
      return;
    }
    super.onItemClick(paramAdapterView, paramView, paramInt, paramLong);
  }

  public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
  {
    L.d(this, "on key down called. " + paramInt);
    if (paramInt == 66)
    {
      onSearchRequested();
      return true;
    }
    return super.onKeyDown(paramInt, paramKeyEvent);
  }

  public boolean onOptionsItemSelected(MenuItem paramMenuItem)
  {
    if (paramMenuItem.getItemId() == 2131165377)
    {
      new SearchRecentSuggestions(this, SearchSuggestProvider.AUTHORITY, 1).clearHistory();
      setHistoryAdapter(null);
      return true;
    }
    return super.onOptionsItemSelected(paramMenuItem);
  }

  public boolean onPrepareOptionsMenu(Menu paramMenu)
  {
    return (this.showingHistory) && (this.mQueryHistoryAdapter.getCount() > 0);
  }

  public void onRestoreInstanceState(Bundle paramBundle)
  {
    super.onRestoreInstanceState(paramBundle);
    Serializable localSerializable1 = paramBundle.getSerializable("keyword");
    if (localSerializable1 != null)
      this.mKeyWord = ((String)localSerializable1);
    Serializable localSerializable2 = paramBundle.getSerializable("extra_notes");
    if (localSerializable2 != null)
    {
      this.mListNoteMetas = ((ListNoteMetas)localSerializable2);
      renderSearchResult();
    }
    L.d(this, "onRestoreInstanceState called.");
  }

  public void onResume()
  {
    super.onResume();
  }

  public void onSaveInstanceState(Bundle paramBundle)
  {
    if (this.mListNoteMetas != null)
      paramBundle.putSerializable("extra_notes", this.mListNoteMetas);
    if (this.mKeyWord != null)
      paramBundle.putString("keyword", this.mKeyWord);
    super.onSaveInstanceState(paramBundle);
    L.d(this, "onSaveInstanceState called.");
  }

  public boolean onSearchRequested()
  {
    this.mKeyWord = this.mTextView.getText().toString();
    performSearch();
    return false;
  }

  public void onStart()
  {
    super.onStart();
  }

  public void onTextChanged(CharSequence paramCharSequence, int paramInt1, int paramInt2, int paramInt3)
  {
  }

  public void onUpdate(int paramInt, BaseData paramBaseData, boolean paramBoolean)
  {
    switch (paramInt)
    {
    default:
      return;
    case 10:
    }
    L.d(this, "Search result got.");
    if (this.mQueryDialog.isShowing())
      dismissDialog(1);
    this.mTextView.clearFocus();
    hideKeyboard(this.mTextView.getWindowToken());
    if (paramBoolean)
    {
      setAndFilterSearchResult((ListNoteMetas)paramBaseData);
      renderSearchResult();
      return;
    }
    UIUtilities.showToast(this, 2131361917);
  }

  class SearchAdapter extends BaseAdapter
    implements Filterable
  {
    private SearchFilter mFilter = null;
    private String[] matchedWords = new String[0];

    public SearchAdapter()
    {
    }

    public int getCount()
    {
      return this.matchedWords.length;
    }

    public Filter getFilter()
    {
      if (this.mFilter == null)
        this.mFilter = new SearchFilter();
      return this.mFilter;
    }

    public Object getItem(int paramInt)
    {
      return this.matchedWords[paramInt];
    }

    public long getItemId(int paramInt)
    {
      return paramInt;
    }

    public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
    {
      View localView = paramView;
      if (localView == null)
        localView = SearchActivity.this.getLayoutInflater().inflate(2130903111, null);
      ((TextView)localView.findViewById(2131165356)).setText((CharSequence)getItem(paramInt));
      localView.setOnClickListener(new View.OnClickListener(paramInt)
      {
        public void onClick(View paramView)
        {
          SearchActivity.access$002(SearchActivity.this, (String)SearchActivity.SearchAdapter.this.getItem(this.val$position));
          SearchActivity.this.mTextView.setText(SearchActivity.this.mKeyWord);
          SearchActivity.this.performSearch();
        }
      });
      return localView;
    }

    class SearchFilter extends Filter
    {
      SearchFilter()
      {
      }

      protected Filter.FilterResults performFiltering(CharSequence paramCharSequence)
      {
        if (paramCharSequence == null)
          return null;
        Filter.FilterResults localFilterResults = new Filter.FilterResults();
        HashSet localHashSet = new HashSet();
        Cursor localCursor = SearchActivity.this.getAllSearchHistory();
        while (true)
        {
          String str;
          try
          {
            CursorHelper localCursorHelper = new CursorHelper(localCursor);
            if (!localCursor.moveToNext())
              break label170;
            str = localCursorHelper.getString("query");
            if ((!str.startsWith((String)paramCharSequence)) || (localHashSet.contains((String)paramCharSequence)))
              break label140;
            L.d(SearchActivity.SearchAdapter.this, "matched query " + str);
          }
          finally
          {
            localCursor.close();
          }
          label140: L.d(SearchActivity.SearchAdapter.this, "unmatched query " + str);
        }
        label170: localFilterResults.values = localHashSet;
        localFilterResults.count = localHashSet.size();
        localCursor.close();
        return localFilterResults;
      }

      protected void publishResults(CharSequence paramCharSequence, Filter.FilterResults paramFilterResults)
      {
        if ((paramFilterResults == null) || (paramFilterResults.count == 0))
        {
          SearchActivity.SearchAdapter.this.notifyDataSetInvalidated();
          return;
        }
        HashSet localHashSet = (HashSet)paramFilterResults.values;
        SearchActivity.SearchAdapter.access$302(SearchActivity.SearchAdapter.this, (String[])localHashSet.toArray(new String[0]));
        SearchActivity.SearchAdapter.this.notifyDataSetChanged();
      }
    }
  }
}

/* Location:           D:\soft\dex2jar-0.0.9.15\classes-dex2jar.jar
 * Qualified Name:     com.youdao.note.activity.SearchActivity
 * JD-Core Version:    0.5.4
 */